package com.cskaoyan.service.impl;

import com.cskaoyan.bean.CskaoyanmallCoupon;
import com.cskaoyan.bean.CskaoyanmallCouponExample;
import com.cskaoyan.bean.CskaoyanmallCouponUser;
import com.cskaoyan.bean.CskaoyanmallCouponUserExample;
import com.cskaoyan.bean.vo.WxCouponMyListVo;
import com.cskaoyan.mapper.CskaoyanmallCouponMapper;
import com.cskaoyan.mapper.CskaoyanmallCouponUserMapper;
import com.cskaoyan.service.WXShoppingService;
import com.cskaoyan.service.WxCouponServiceZGY;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
public class WxCouponServiceImplZGY implements WxCouponServiceZGY {

    @Autowired
    CskaoyanmallCouponMapper mapper;

    @Autowired
    CskaoyanmallCouponUserMapper mapperUserCoupon;


    @Override
    public WxCouponMyListVo wxListCoupon(Integer status, Integer page, Integer size, Integer userId) {

//        先根据userId和status查出对应的couponId
        CskaoyanmallCouponUserExample couponUserExample = new CskaoyanmallCouponUserExample();
        CskaoyanmallCouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andStatusEqualTo(((short) status.intValue()));

        List<CskaoyanmallCouponUser> couponUsers = mapperUserCoupon.selectByExample(couponUserExample);

//        初始化一个数组用来接收couponIds
        ArrayList<Integer> couponIds = new ArrayList<>();

        Iterator<CskaoyanmallCouponUser> iterator = couponUsers.iterator();
        int i = 0;
        while (iterator.hasNext()) {
            couponIds.add(iterator.next().getCouponId());
        }

//        去优惠券表中查优惠券
        List<CskaoyanmallCoupon> couponList = new ArrayList<>();

        CskaoyanmallCouponExample cskaoyanmallCouponExample = new CskaoyanmallCouponExample();
        CskaoyanmallCouponExample.Criteria criteria1 = cskaoyanmallCouponExample.createCriteria();
        criteria1.andIdIn(couponIds);

        PageHelper.startPage(page, size);
        List<CskaoyanmallCoupon> coupons = mapper.selectByExample(cskaoyanmallCouponExample);
        PageInfo<CskaoyanmallCoupon> couponPageInfo = new PageInfo<>(coupons);
        long total = couponPageInfo.getTotal();

        WxCouponMyListVo wxCouponMyListVo = new WxCouponMyListVo();
        wxCouponMyListVo.setCount(total);
        wxCouponMyListVo.setData(coupons);

        return wxCouponMyListVo;
    }


    /**
     * 首页上点击优惠券标题，显示所有的优惠券
     */
    @Override
    public WxCouponMyListVo queryCoupons(Integer page, Integer size) {

        PageHelper.startPage(page, size);
        CskaoyanmallCouponExample cskaoyanmallCouponExample = new CskaoyanmallCouponExample();
        CskaoyanmallCouponExample.Criteria criteria = cskaoyanmallCouponExample.createCriteria();
        criteria.andDeletedEqualTo(false);

        List<CskaoyanmallCoupon> coupons = mapper.selectByExample(cskaoyanmallCouponExample);
        PageInfo<CskaoyanmallCoupon> couponPageInfo = new PageInfo<>(coupons);
        long total = couponPageInfo.getTotal();

        WxCouponMyListVo wxCouponVo = new WxCouponMyListVo();
        wxCouponVo.setData(coupons);
        wxCouponVo.setCount(total);

        return wxCouponVo;
    }

    @Override
    public Boolean receiveCoupon(Integer couponId, Integer userId) {

//        先根据userId验证是否领取过该优惠券
//        TODO: 优惠券有单人限领数量！limit字段
        CskaoyanmallCouponUserExample couponUserExample = new CskaoyanmallCouponUserExample();
        CskaoyanmallCouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andCouponIdEqualTo(couponId);
        criteria.andUserIdEqualTo(userId);
        criteria.andStatusEqualTo((short) 0);

        List<CskaoyanmallCouponUser> cskaoyanmallCouponUsers = mapperUserCoupon.selectByExample(couponUserExample);
        if (cskaoyanmallCouponUsers != null && cskaoyanmallCouponUsers.size() > 0) {
            return false;
        }

//        若用户当前没有该优惠券，则可以领取。先到优惠券表中查出优惠券的startTime和endTime，然后再往User_Coupon中insert数据
//        领取优惠券时，若优惠券数量为1，则领取后，将优惠券进行逻辑删除

        CskaoyanmallCoupon coupon = mapper.selectByPrimaryKey(couponId);
        Date startTime = coupon.getStartTime();
        Date endTime = coupon.getEndTime();

//        如果此时，优惠券的数量(total)为1，则对该优惠券进行一个逻辑删除
        if (coupon.getTotal() == 1) {
            mapper.updateDeleted(true, couponId);
        }

//        逻辑删除之后，给user_coupon表执行insert
        CskaoyanmallCouponUser couponUser = new CskaoyanmallCouponUser();
        couponUser.setStartTime(startTime);
        couponUser.setEndTime(endTime);
        couponUser.setAddTime(new Date());
        couponUser.setUpdateTime(new Date());
        couponUser.setCouponId(couponId);
        couponUser.setUserId(userId);
        couponUser.setStatus((short)0);
        couponUser.setDeleted(false);


        mapperUserCoupon.insertSelective(couponUser);


        return true;
    }

    @Override
    public List<CskaoyanmallCoupon> queryAvailableCoupons(Integer cartId,
                                                          Integer grouponRulesId, Integer userId) {


//        先对userCoupon表做查询
        CskaoyanmallCouponUserExample couponUserExample = new CskaoyanmallCouponUserExample();
        CskaoyanmallCouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andStatusEqualTo(((short) 0));
        criteria.andUserIdEqualTo(userId);

//        TODO: 用户没有优惠券的情况下，有空指针异常

        List<CskaoyanmallCouponUser> couponUsers = mapperUserCoupon.selectByExample(couponUserExample);

//        用户没有任何优惠券的情况
        if (couponUsers == null) {
            return new ArrayList<>();
        }

        List<Integer> integers = new ArrayList<>();

//        封装查询出的id
        Iterator<CskaoyanmallCouponUser> iterator = couponUsers.iterator();
        while (iterator.hasNext()) {
            integers.add(iterator.next().getCouponId());
        }

//        使用couponids查询符合条件的优惠券
        CskaoyanmallCouponExample couponExample = new CskaoyanmallCouponExample();
        CskaoyanmallCouponExample.Criteria criteria1 = couponExample.createCriteria();
        criteria1.andStatusEqualTo(((short) 0));
        criteria1.andDeletedEqualTo(false);
        if (integers.size()!=0) {
            criteria1.andIdIn(integers);
        }

        List<CskaoyanmallCoupon> cskaoyanmallCoupons = mapper.selectByExample(couponExample);

//        筛掉过期的优惠券-->与当前时间对比是否过期
//        TODO: 应判断当前时间是否在优惠券的有效区间内
        Date timeNow = new Date();
        for (int i = 0; i < cskaoyanmallCoupons.size(); i++) {
            CskaoyanmallCoupon coupon = cskaoyanmallCoupons.get(i);
            if (coupon.getEndTime() != null && coupon.getEndTime().before(timeNow)) {
                cskaoyanmallCoupons.remove(i);
            }
        }

//        判断是否满足满减金额
        BigDecimal goodsTotalPrice = WXShoppingServiceImpl.goodsTotalPrice;

        return cskaoyanmallCoupons;
    }

    @Override
    public Boolean exchangeCoupons(String code, Integer userId) {

//        先根据code 查coupon表 判断是否有符合条件的优惠券
        CskaoyanmallCouponExample couponExample = new CskaoyanmallCouponExample();
        CskaoyanmallCouponExample.Criteria criteria = couponExample.createCriteria();
        criteria.andStatusEqualTo(((short) 0));
        criteria.andCodeEqualTo(code);
        criteria.andDeletedEqualTo(false);

        List<CskaoyanmallCoupon> coupons = mapper.selectByExample(couponExample);
        if (coupons.size() == 0) {
            return false;
        }

//        获取优惠券的id、startTime、endTime --> User_coupon
        Integer id = coupons.get(0).getId();
        Date startTime = coupons.get(0).getStartTime();
        Date endTime = coupons.get(0).getEndTime();

        CskaoyanmallCouponUser couponUser = new CskaoyanmallCouponUser();
        couponUser.setUserId(userId);
        couponUser.setCouponId(id);
        couponUser.setStartTime(startTime);
        couponUser.setEndTime(endTime);
        couponUser.setAddTime(new Date());
        couponUser.setUpdateTime(new Date());
        couponUser.setStatus(((short) 0));
        couponUser.setDeleted(false);

        mapperUserCoupon.insertSelective(couponUser);

        return true;
    }
}
